import { _decorator, assetManager, CCInteger, Component, ImageAsset, instantiate, Label, loader, Node, Sprite, spriteAssembler, SpriteFrame, Texture2D, Toggle, UIOpacity, UITransform } from 'cc';
import { AppControll, ConfigKey } from '../manager/AppControll';
import { load } from '../ui/Load';
import { GameData } from '../system/GameData';
import { Tools } from '../tools/Tools';
import { SoundManager } from '../manager/SoundManger';
import { DataHelper } from '../system/DataHelper';
import { RankNormalItem } from './RankNormalItem';
import { ListView } from '../tools/ListView';
const { ccclass, property } = _decorator;

export type rankData = {
    _id: string;
    headImg: string,
    honor: number,
    nickName: string
}

export type levelData = {
    _id: string;
    headImg: string,
    level: number,
    time: number
    nickName: string
}

enum rankModel {
    default,
    rank,
    levelRank
}

@ccclass('Rank')
export class Rank extends Component {
    @property(Node)
    mContent: Node = null;
    @property(Node)
    mRankItem: Node = null;
    @property(Node)
    mLevelRItem: Node = null;
    @property(CCInteger)
    mNUpdataTime = 60;
    @property(CCInteger)
    mNMaxLoad = 20;
    @property(Node)
    mNdRankView: Node = null;
    @property(Node)
    mNdLevelView: Node = null;

    private mRankList: rankData[] = null;
    private mCurTime = 0;
    private mMyRank = -1;
    private mMyLevelRank = -1;
    private mMyRankData = null;
    private mMyLevelData = null;
    private mCurModel = rankModel.default;
    private mLevelData: levelData[] = null;
    private mNdTogRank: Toggle = null;
    private mNdTogLevel: Toggle = null;
    private mNdLevelTitle: Node = null;
    private mNdTitle: Node = null;
    private mNdRankSelf: Node = null;
    private mNdLevelRSelf: Node = null;
    private mCurList = null;
    private mIsInitRank = false;
    private mIsInitLevel = false;
    private mIsFinishData = 0;


    protected onLoad(): void {
        GameData.isPause = true;
        this.node.getChildByName("body").getChildByName("selfRank").active = false;
        let ndBody = this.node.getChildByName("body");
        let ndSelect = ndBody.getChildByName("btnSelect");
        this.mNdTogRank = ndSelect.getChildByName("ToggleGroup").getChildByName("Toggle1").getComponent(Toggle);
        this.mNdTogLevel = ndSelect.getChildByName("ToggleGroup").getChildByName("Toggle2").getComponent(Toggle);
        this.mNdRankSelf = this.node.getChildByName("body").getChildByName("selfRank");
        this.mNdLevelRSelf = this.node.getChildByName("body").getChildByName("selfLevelRank");
        this.mNdLevelTitle = ndBody.getChildByName("levelTitle");
        this.mNdTitle = ndBody.getChildByName("honorTitle");
        this.UpdateData();
    }

    UpdateData() {
        AppControll.Platform.GetRankList((res) => {
            this.mRankList = res;
            AppControll.Platform.UpdateRank();
            if (this.node) this.node.getChildByName("loading").active = false;;
            this.mCurModel = rankModel.rank;
            this.ShowModel();
        });
        AppControll.Platform.GetLevelRank((mLevelData) => {
            this.mLevelData = mLevelData;
            this.mIsFinishData++;
            if (this.mIsFinishData == 2) {
                if (this.mNdTogLevel) this.mNdTogLevel.interactable = true;
            }
        })
        AppControll.Platform.GetMyLevelR((mylevel) => {
            this.mMyLevelData = mylevel;
            this.mIsFinishData++;
            if (this.mIsFinishData == 2) {
                if (this.mNdTogLevel) this.mNdTogLevel.interactable = true;
            }
        })
    }

    InitRankView() {
        if (this.mIsInitRank) return;
        if (!this.mIsInitRank) {
            this.mIsInitRank = true;
        }

        if (!GameData.userInfo) return;
        if (!this.mRankList) return;
        if (this.mRankList.length == 0) return;

        let selfRankData: rankData = {
            _id: '',
            headImg: '',
            honor: 0,
            nickName: ''
        };
        selfRankData._id = GameData.openId;
        selfRankData.headImg = GameData.userInfo.avatarUrl;
        selfRankData.honor = GameData.playerData.Honor;
        selfRankData.nickName = GameData.userInfo.nickName;
        this.mMyRankData = selfRankData;

        for (let i = 0; i < this.mRankList.length; i++) {
            if (this.mRankList[i]._id == GameData.openId) {
                this.mRankList.splice(i, 1);
            }
        }

        for (let i = 0; i < this.mRankList.length; i++) {
            if (this.mRankList[i].honor <= GameData.playerData.Honor) {
                this.mMyRank = i;
                break;
            }
        }

        let selfRankNode = this.node.getChildByName("body").getChildByName("selfRank");
        if (this.mMyRank != -1) {
            if (!this.mRankList[this.mMyRank]) return;
            if (this.mRankList[this.mMyRank]._id != GameData.openId) {
                this.mRankList.splice(this.mMyRank, 0, this.mMyRankData);
            }
            if (selfRankData.nickName != DataHelper.GetConfigByKey(ConfigKey.defaultUserName).value) {
                selfRankNode.getChildByName("headIcon").getChildByName("Mask").getChildByName("icon").getComponent(Sprite).spriteFrame = null;
            }
        }

        this.mCurList = this.mRankList;
        this.mNdRankView.getComponent(ListView).InitListView(this.mCurList, "RankNormalItem");

        this.InitSelf();
    }

    InitLevelRankView() {
        if (this.mIsInitLevel) return;
        if (!this.mIsInitLevel) {
            this.mIsInitLevel = true;
        }
        if (!GameData.userInfo) return;
        if (!this.mLevelData) return;
        if (this.mLevelData.length == 0) return;

        let selfRankData: levelData = {
            _id: '',
            headImg: '',
            level: 0,
            nickName: '',
            time: 0
        };
        selfRankData._id = GameData.openId;
        selfRankData.headImg = GameData.userInfo.avatarUrl;
        selfRankData.level = 0;
        selfRankData.time = 0;
        selfRankData.nickName = GameData.userInfo.nickName;

        this.mLevelData.sort((a, b) => {
            if (a.level == b.level) {
                return a.time - b.time;
            } else {
                return b.level - a.level;
            }
        })

        for (let i = 0; i < this.mLevelData.length; i++) {
            if (this.mLevelData[i]._id == GameData.openId) {
                this.mMyLevelRank = i;
            }
        }


        let selfRankNode = this.node.getChildByName("body").getChildByName("selfLevelRank");
        if (this.mMyLevelRank != -1) {
            if (this.mLevelData[this.mMyLevelRank]._id != GameData.openId) {
                this.mLevelData.splice(this.mMyLevelRank, 0, this.mMyLevelData);
            }
            if (selfRankData.nickName != DataHelper.GetConfigByKey(ConfigKey.defaultUserName).value) {
                selfRankNode.getChildByName("headIcon").getChildByName("Mask").getChildByName("icon").getComponent(Sprite).spriteFrame = null;
            }
        }

        this.mCurList = this.mLevelData;
        this.mNdLevelView.getComponent(ListView).InitListView(this.mCurList, "RankLevelItem");
        this.InitLevelSelf();
    }

    InitSelf() {
        if (!this.mRankList) return;
        if (this.mRankList.length == 0) return;
        let selfRankNode = this.node.getChildByName("body").getChildByName("selfRank");
        selfRankNode.active = true;
        let icon = selfRankNode.getChildByName("headIcon").getChildByName("Mask").getChildByName("icon");
        icon.active = false;
        let str = this.mMyRank == -1 ? "100+" : (this.mMyRank + 1) + "";
        selfRankNode.getChildByName("ranNum").getComponent(Label).string = str;
        selfRankNode.getChildByName("name").getComponent(Label).string = this.mMyRankData.nickName;
        selfRankNode.getChildByName("honorNum").getComponent(Label).string = Tools.FormatNumber(GameData.playerData.Honor);
        if (this.mMyRank != -1 || this.mMyRankData.headImg == "" || this.mMyRankData.headImg == DataHelper.GetConfigByKey(ConfigKey.defaultUserName).value) {
            icon.active = true;
            return;
        }
        assetManager.loadRemote(this.mMyRankData.headImg, { ext: '.png' }, (error1, img: ImageAsset) => {
            let texture = new Texture2D();
            texture.image = img;
            icon.active = true;
            let newSpriteFrame = new SpriteFrame();
            newSpriteFrame.texture = texture;
            newSpriteFrame.packable = false;
            icon.getComponent(Sprite).spriteFrame = newSpriteFrame;
        })
    }

    InitLevelSelf() {
        if (!this.mMyLevelData) {
            let selfRankData: levelData = {
                _id: '',
                headImg: '',
                level: 0,
                nickName: '',
                time: 0
            };
            selfRankData._id = GameData.openId;
            selfRankData.headImg = GameData.userInfo.avatarUrl;
            selfRankData.level = 0;
            selfRankData.time = 0;
            selfRankData.nickName = GameData.userInfo.nickName;
            this.mMyLevelData = selfRankData
        } else {
            this.mMyLevelData["headImg"] = GameData.userInfo ? GameData.userInfo.avatarUrl : "";
            this.mMyLevelData["nickName"] = GameData.userInfo ? GameData.userInfo.nickName : "";
        }
        let selfRankNode = this.node.getChildByName("body").getChildByName("selfLevelRank");
        selfRankNode.active = true;
        let icon = selfRankNode.getChildByName("headIcon").getChildByName("Mask").getChildByName("icon");
        icon.active = false;
        let str = this.mMyLevelRank == -1 ? "100+" : (this.mMyLevelRank + 1) + "";
        selfRankNode.getChildByName("ranNum").getComponent(Label).string = str;
        selfRankNode.getChildByName("name").getComponent(Label).string = this.mMyLevelData.nickName;
        selfRankNode.getChildByName("levelNum").getComponent(Label).string = this.mMyLevelData.level;
        selfRankNode.getChildByName("useTimme").getComponent(Label).string = this.mMyLevelData.time.toFixed(2);
        if (this.mMyLevelData.headImg == "" || this.mMyLevelData.headImg == DataHelper.GetConfigByKey(ConfigKey.defaultUserName).value) {
            icon.active = true;
            return;
        }
        assetManager.loadRemote(this.mMyLevelData.headImg, { ext: '.png' }, (error1, img: ImageAsset) => {
            let texture = new Texture2D();
            texture.image = img;
            icon.active = true;
            let newSpriteFrame = new SpriteFrame();
            newSpriteFrame.texture = texture;
            newSpriteFrame.packable = false;
            if (icon.getComponent(Sprite)) icon.getComponent(Sprite).spriteFrame = newSpriteFrame;
        })
    }

    update(deltaTime: number) {

    }

    protected onDestroy(): void {
        GameData.isPause = false;
    }

    OnClose() {
        GameData.isPause = false;
        this.mIsInitLevel = false;
        this.mIsInitRank = false;
        AppControll.ShelvedTime = 0;
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        this.mContent.destroyAllChildren();
        this.node.destroy();
    }

    OnBtnShare() {
        AppControll.ShelvedTime = 0;
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        AppControll.Platform.Share();
    }

    OnChangeModel() {
        if (this.mNdTogLevel.isChecked) {
            if (this.mCurModel == rankModel.levelRank)
                return;
            this.mCurModel = rankModel.levelRank;
        } else if (this.mNdTogRank.isChecked) {
            if (this.mCurModel == rankModel.rank)
                return;
            this.mCurModel = rankModel.rank;
        }
        this.ShowModel();
    }

    ShowModel() {
        if (!this.node) return;
        switch (this.mCurModel) {
            case rankModel.levelRank:
                if (this.mNdTitle) this.mNdTitle.active = false;
                if (this.mNdLevelTitle) this.mNdLevelTitle.active = true;
                if (this.mNdRankSelf) this.mNdRankSelf.active = false;
                if (this.mNdLevelRSelf) this.mNdLevelRSelf.active = true;
                if (this.mNdRankView) this.mNdRankView.active = false;
                if (this.mNdLevelView) this.mNdLevelView.active = true;
                this.InitLevelRankView();
                break;
            case rankModel.rank:
                if (this.mNdTitle) this.mNdTitle.active = true;
                if (this.mNdLevelTitle) this.mNdLevelTitle.active = false;
                if (this.mNdRankSelf) this.mNdRankSelf.active = true;
                if (this.mNdLevelRSelf) this.mNdLevelRSelf.active = false;
                if (this.mNdRankView) this.mNdRankView.active = true;
                if (this.mNdLevelView) this.mNdLevelView.active = false;
                this.InitRankView();
                break;
        }
    }

}


